package com.jubaozan.service.platform.decorator;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jubaozan.c3.framework.utils.ObjectUtil;
import com.jubaozan.c3.framework.utils.ResultHolder;
import com.jubaozan.dao.youme.domain.*;
import com.jubaozan.dao.youme.service.*;
import com.jubaozan.dao.youme.service.IdcardService;
import com.jubaozan.dao.youme.service.StoreService;
import com.jubaozan.feign.user.UserFeignService;
import com.jubaozan.feign.user.constants.UserTypeEnum;
import com.jubaozan.feign.user.vo.UserCreationVO;
import com.jubaozan.feign.user.vo.UserVO;
import com.jubaozan.service.platform.constants.PlatformConstants;
import com.jubaozan.service.platform.constants.PlatformStatusEnum;
import com.jubaozan.service.platform.constants.PlatformTypeEnum;
import com.jubaozan.service.platform.exception.PlatformException;
import com.jubaozan.service.platform.vo.PlatformInfoVO;
import com.jubaozan.service.platform.vo.PlatformProgressVO;
import com.jubaozan.service.platform.vo.PlatformSubmitVO;
import com.jubaozan.service.platform.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.session.StoreType;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @ClassName PlatformRegisterDecorator
 * @Description 个体平台入驻Decorator
 * @Author TanRuixiang
 * @Date 2020/9/17 16:28
 * @Version 1.0
 **/
@Slf4j
@Component
public class PlatformRegisterDecorator {
    private final StoreService storeService;

    private final IdcardService idcardService;

    private final CompanyService companyService;

    private final UserFeignService userFeignService;

    private final StoreAuditService storeAuditService;

    private final ConfigureProperties configureProperties;

    private final StoreUserAuditService storeUserAuditService;

    public PlatformRegisterDecorator(StoreService storeService, IdcardService idcardService,
                                     CompanyService companyService, UserFeignService userFeignService,
                                     StoreAuditService storeAuditService, ConfigureProperties configureProperties,
                                     StoreUserAuditService storeUserAuditService) {
        this.storeService = storeService;
        this.idcardService = idcardService;
        this.companyService = companyService;
        this.userFeignService = userFeignService;
        this.storeAuditService = storeAuditService;
        this.configureProperties = configureProperties;
        this.storeUserAuditService = storeUserAuditService;

    }

    /**
     * @param platformInfoVO:
     * @return
     * @Author TanRuixiang
     * @Description 个体平台资料注册
     * @Date 2020年09月18日 11:15
     **/
    public Boolean register(PlatformInfoVO platformInfoVO) throws PlatformException {
        UserVO userVO = createUser(platformInfoVO);
        Store store = registerCheck(platformInfoVO,userVO);
        BeanUtils.copyProperties(platformInfoVO, store);
        logger.info("收到用户入驻申请信息:{}", platformInfoVO);
        if (store.getType().equals(PlatformTypeEnum.ENTERPRISE_PLATFORM.type())) {
            store.setStatus(PlatformStatusEnum.WAIT_AUDIT.status());
        } else {
            store.setStatus(PlatformStatusEnum.WAIT_SUBMIT.status());
        }
        store.setRequireScreenshot(false);
        store.setUserId(userVO.getId());
        return storeService.saveOrUpdate(store);
    }

    /**
     * @Author TanRuixiang
     * @Description 创建用户
     * @Date 2020年10月04日 11:32
     * @param platformInfoVO:
     * @return
     **/
    private UserVO createUser(PlatformInfoVO platformInfoVO){
        platformInfoVO.setUserType(UserTypeEnum.MP);
        UserCreationVO creation = new UserCreationVO();
        BeanUtils.copyProperties(platformInfoVO, creation);
        creation.setType(platformInfoVO.getUserType());
       ResultHolder<UserVO> holder = userFeignService.createUser(creation);
        UserVO userVO = holder.getBody();
        if (ObjectUtil.isEmpty(userVO)) {
            throw new PlatformException("创建用户失败");
        }
        return userVO;
    }

    /**
     * @Author TanRuixiang
     * @Description 注册前校验
     * @Date 2020年10月04日 11:32
     * @param platformInfoVO:
     * @param userVO:
     * @return
     **/
    private Store registerCheck(PlatformInfoVO platformInfoVO,UserVO userVO){
        Store store = getStoreByParams(new Store().setMobile(platformInfoVO.getMobile()));
        if (ObjectUtil.isNotEmpty(store) && !store.getUnionid().equals(platformInfoVO.getUnionid())) {
            throw new PlatformException("手机号已被注册");
        }
        store = getStoreByParams(new Store().setUnionid(userVO.getUnionid()));
        if (ObjectUtil.isEmpty(store)) {
            store = new Store();
        }
        return store;
    }
    /**
     * @param store:
     * @return
     * @Author TanRuixiang
     * @Description 通过unionid查询个体平台信息
     * @Date 2020年09月21日 15:49
     **/
    private Store getStoreByParams(Store store) {
        QueryWrapper<Store> qw = new QueryWrapper<>();
        if (ObjectUtil.isNotEmpty(store.getUnionid())) {
            qw.eq("unionid", store.getUnionid());
        }
        if (ObjectUtil.isNotEmpty(store.getMobile())) {
            qw.eq("mobile", store.getMobile());
        }
        return storeService.getOne(qw);
    }


    /**
     * @param idcardNo: 身份证号码
     * @return
     * @Author TanRuixiang
     * @Description 通过身份证号码查询身份证信息
     * @Date 2020年09月21日 15:49
     **/
    private Idcard getIdcardByidcardNo(String idcardNo) {
        QueryWrapper<Idcard> qw = new QueryWrapper<>();
        qw.eq("idcard_no", idcardNo);
        Idcard idcard = this.idcardService.getOne(qw);
        if (ObjectUtil.isEmpty(idcard)) {
            idcard = new Idcard();
        }
        return idcard;
    }

    /**
     * @param id:
     * @return
     * @Author TanRuixiang
     * @Description 根据主键ID查询企业信息对象
     * @Date 2020年09月22日 10:45
     **/
    private Company getCompanyById(Long id) {
        return companyService.getById(id);
    }

    /**
     * @param platformSubmitVO:
     * @return
     * @Author TanRuixiang
     * @Description 个体平台资料提交
     * @Date 2020年09月18日 11:59
     **/
    @Transactional(propagation = Propagation.REQUIRED)
    public Boolean submit(PlatformSubmitVO platformSubmitVO) {

        Store store = getStoreByParams(new Store().setUnionid(platformSubmitVO.getUnionid()));
        if (ObjectUtil.isEmpty(store)) {
            throw new PlatformException("用户未提交注册基本信息");
        }
        if (!store.getType().equals(PlatformTypeEnum.PERSONAL_PLATFORM.type())) {
            throw new PlatformException("用户注册类型不一致");
        }
        Idcard idcard = this.getIdcardByidcardNo(platformSubmitVO.getIdcardNo());
        store.setIdcardNo(platformSubmitVO.getIdcardNo());
        store.setStatus(PlatformStatusEnum.WAIT_AUDIT.status());
        BeanUtils.copyProperties(platformSubmitVO, idcard);
        idcard.setCreateBy(String.valueOf(store.getUserId()));
        idcardService.saveOrUpdate(idcard);
        return storeService.saveOrUpdate(store);
    }

    /**
     * @param platformCompanySubmitVO:
     * @return
     * @Author TanRuixiang
     * @Description 企业入驻资料提交
     * @Date 2020年09月18日 18:50
     **/
    @Transactional(propagation = Propagation.REQUIRED)
    public Boolean companySubmit(PlatformCompanySubmitVO platformCompanySubmitVO) {
        Store store = getStoreByParams(new Store().setUnionid(platformCompanySubmitVO.getUnionid()));
        if (ObjectUtil.isEmpty(store)) {
            throw new PlatformException("用户未提交注册基本信息");
        }
        if (!store.getType().equals(PlatformTypeEnum.ENTERPRISE_PLATFORM.type())) {
            throw new PlatformException("用户注册类型不一致");
        }
        //添加身份证信息
        Idcard idcard = this.getIdcardByidcardNo(platformCompanySubmitVO.getCorporationIdcard());
        BeanUtils.copyProperties(platformCompanySubmitVO.getPlatformSubmitVO(), idcard);
        idcard.setCreateBy(String.valueOf(store.getUserId()));
        idcard.setIdcardNo(platformCompanySubmitVO.getCorporationIdcard());
        idcard.setExpireDate(platformCompanySubmitVO.getExpireDate());
        idcard.setName(platformCompanySubmitVO.getCorporation());
        idcardService.saveOrUpdate(idcard);
        //添加营业执照信息
        Company company = this.getCompanyById(store.getCompanyId());
        if (ObjectUtil.isEmpty(company)) {
            company = new Company();
        }
        BeanUtils.copyProperties(platformCompanySubmitVO, company);
        company.setCreateBy(String.valueOf(store.getUserId()));
        companyService.saveOrUpdate(company);
        //更新基础信息补全
        store.setCompanyId(company.getId());
        store.setStatus(PlatformStatusEnum.WAIT_REPEAT_AUDIT.status());
        store.setIdcardNo(platformCompanySubmitVO.getCorporationIdcard());
        return storeService.saveOrUpdate(store);
    }

    /**
     * @param unionid:
     * @return
     * @Author TanRuixiang
     * @Description 查询用户申请进度和邀请人信息
     * @Date 2020年09月18日 15:48
     **/
    public PlatformProgressVO queryProgress(String unionid) {
        PlatformProgressVO platformProgressVO = new PlatformProgressVO();
        Store store = this.getStoreByParams(new Store().setUnionid(unionid));
        if (ObjectUtil.isEmpty(store)) {
            return null;
        }
        platformProgressVO.setMobile(store.getMobile());
        platformProgressVO.setStatus(store.getStatus());
        platformProgressVO.setCreateAt(store.getCreateAt());
        platformProgressVO.setRefereeName(store.getRefereeName());
        platformProgressVO.setFirstAudit(store.getFirstAudit());
        Idcard idcard = this.getIdcardByidcardNo(store.getIdcardNo());
        if (ObjectUtil.isNotEmpty(idcard.getName())) {
            platformProgressVO.setName(idcard.getName());
        }
        ResultHolder<UserVO> holder = userFeignService.getUserById(store.getRefereeId());
        UserVO userVO = holder.getBody();
        if (holder.isSuccess() && ObjectUtil.isNotEmpty(userVO)) {
            platformProgressVO.setRefereeMobile(userVO.getMobile());
            platformProgressVO.setRefereeAvatar(userVO.getAvatar());
        }
        return platformProgressVO;
    }

    /**
     * @param storeId: 平台ID
     * @param level:   等级ID
     * @return
     * @Author TanRuixiang
     * @Description 获取团长待审核数
     * @Date 2020年09月29日 14:49
     **/
    public Integer getAuditTeamsNum(Long storeId, Integer level) {
        QueryWrapper<StoreUserAudit> qw = new QueryWrapper<>();
        qw.lambda().eq(StoreUserAudit::getStoreId, storeId)
                .eq(StoreUserAudit::getTargetLevel, level)
                .eq(StoreUserAudit::getStatus, PlatformStatusEnum.WAIT_AUDIT);
        return storeUserAuditService.count(qw);
    }

    /**
     * @param unionid:
     * @return
     * @Author TanRuixiang
     * @Description 检查入驻审核状态和情况
     * @Date 2020年09月18日 21:21
     **/
    public StoreVO checkStore(String unionid) {
        Store store = this.getStoreByParams(new Store().setUnionid(unionid));
        if (ObjectUtil.isEmpty(store)) {
            return null;
        }
        StoreVO storeVO = this.composeStoreVO(store);
        StoreAudit storeAudit = this.getStoreAuditByStoreId(store.getId());
        storeVO.setStoreAudit(storeAudit);
        return storeVO;
    }

    /**
     * @param unionid:
     * @return
     * @Author TanRuixiang
     * @Description 查询门店基础信息, 身份信息, 企业信息
     * @Date 2020年09月18日 22:01
     **/
    public StoreVO queryStore(String unionid) {
        Store store = this.getStoreByParams(new Store().setUnionid(unionid));
        if (ObjectUtil.isEmpty(store)) {
            return null;
        }
        StoreVO storeVO = this.composeStoreVO(store);
        return storeVO;
    }

    /**
     * @param storeId:
     * @return
     * @Author TanRuixiang
     * @Description 根据门店ID查询门店的审核记录
     * @Date 2020年09月18日 21:21
     **/
    private StoreAudit getStoreAuditByStoreId(Long storeId) {
        QueryWrapper<StoreAudit> qw = new QueryWrapper<>();
        qw.eq("store_id", storeId);
        return storeAuditService.getOne(qw);
    }

    /**
     * @param store:
     * @return
     * @Author TanRuixiang
     * @Description 组合门店基础信息, 身份信息, 企业信息
     * @Date 2020年09月18日 22:00
     **/
    private StoreVO composeStoreVO(Store store) {
        StoreVO storeVO = new StoreVO();
        BeanUtils.copyProperties(store, storeVO);
        if (store.getStatus().equals(PlatformStatusEnum.PASS_AUDIT.status())) {
            return storeVO;
        }
        Idcard idcard = this.getIdcardByidcardNo(store.getIdcardNo());
        storeVO.setIdcard(idcard);
        if (store.getType().equals(PlatformTypeEnum.ENTERPRISE_PLATFORM.type())) {
            Company company = this.getCompanyById(store.getCompanyId());
            storeVO.setCompany(company);
        }
        return storeVO;
    }

    /**
     * @param :
     * @return
     * @Author TanRuixiang
     * @Description 小程序配置信息
     * @Date 2020年09月21日 15:50
     **/
    public ConfigureProperties configure() {
        return configureProperties;
    }


    private UserVO getUserByUnionid(String unionid) {
        ResultHolder<UserVO> holder = userFeignService.getUserByUnionid(null, unionid);
        return holder.getBody();
    }
}
